package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * kafka生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //kafka的配置信息
        Properties properties = new Properties();
        //配置kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "8.142.73.187:9092");
        //发送失败重试的次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //ack
        properties.put(ProducerConfig.ACKS_CONFIG, "1");//只要集群首领节点收到消息，生产者就会收到一个来自服务器的成功响应

        //生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);

        //封装发送的消息
        ProducerRecord<String, String> record = new ProducerRecord<String, String>("itheima-topic", "1000", "hello kafka");

        /*//发送消息
        RecordMetadata recordMetadata = kafkaProducer.send(record).get();
        //获取偏移量
        System.out.println(recordMetadata.offset());*/

       kafkaProducer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("消息生产者发生异常");
                }
                long offset = recordMetadata.offset();
                System.out.println(offset);

            }
        });

        //关闭通道
        kafkaProducer.close();

    }
}
